﻿/**
as3app - An open-source ActionScript 3.0 Library developed to assist 
in creating simple visual controls/data binding/asset loading for the
Flash player platform.

http://code.google.com/p/as3app/

Copyright (c) 2011 M. K. Chowdhury, All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package as3app.visuals
{
	import com.funrock.FireGame.Util.SpriteEvent;
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;
	
	import as3app.visuals.events.SliderEvent;
	/**
	 * ...
	 * @author Muntasir Kabir Chowdhury
	 * 
	 * @todo
	 * Users should be able to configure Slider type vertical or horizontal. 
	 */
	public class Slider extends Sprite
	{
		public var sliderWidth:Number = 300;
		public var sliderHeight:Number = 20;
		
		
		
		
		/**
		 * Private vars
		 */
		private var pathWidthRatio:Number = 1;
		private var pathOriginalWidth:Number = 1;
		private var path:DisplayObject = null;
		private var pathSprite:Sprite = new Sprite();
		private var _pointerDisplayObject:DisplayObject = null;
		private var pointer:Sprite = new Sprite();
		private var filledPath:DisplayObject = null;
		private var _value:Number = 0;
		private var _minValue:Number = 0;
		private var _maxValue:Number = 1;
		private var _range:Number = 1;
		private var _slidingSencitivity:Number = 50;
		private var timer:Timer = new Timer(_slidingSencitivity);
		private var dragging:Boolean = false;
		private var _hasValueChangeHandler:Boolean = false;
		
		
		
		
		/**
		 * Overriden methods
		 */
		
		 
		/**
		 * addEventListener
		 * @param	type
		 * @param	listener
		 * @param	useCapture
		 * @param	priority
		 * @param	useWeakReference
		 */
		override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void 
		{
			super.addEventListener(type, listener, useCapture, priority, useWeakReference);
			resetEventGeneration(type);
		}
		
		
		
		/**
		 * removeEventListener
		 * @param	type
		 * @param	listener
		 * @param	useCapture
		 */
		override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void 
		{
			super.removeEventListener(type, listener, useCapture);
			resetEventGeneration(type);
		}
		
		
		
		
		
		
		/**
		 * Get or set the delay of updating the value while sliding from ui.
		 */
		public function get SlidingSencitivity():Number { return _slidingSencitivity; }
		public function set SlidingSencitivity(slidingSencitivity:Number) {  _slidingSencitivity = slidingSencitivity; timer.delay = _slidingSencitivity; }
		
		
		
		
		
		
		/**
		 * Get minimun value.
		 */
		public function get Min():Number { return _minValue; }
		
		
		
		
		
		
		/**
		 * Get maximum value.
		 */
		public function get Max():Number { return _maxValue; }
		
		
		
		
		
		
		/**
		 * Set range or window of values
		 * @param	minValue
		 * @param	maxValue
		 */
		public function SetRange(minValue:Number, maxValue:Number)
		{
			if (minValue <= maxValue)
			{
				_minValue = minValue;
				_maxValue = maxValue;
				_range = _maxValue-_minValue;
				validate();
			}
		}
		
		
		
		
		
		
		
		/**
		 * Get or set the value.
		 */
		public function get Value():Number { return _value; }
		public function set Value(newValue:Number) 
		{  
			
			_value = newValue;
			validate();
			
			// Update UI
			if (_value == _minValue) 
			{
				filledPath.visible = false;
				pointer.x = 0;
			}
			else
			{
				filledPath.width = (_value-_minValue) / _range * sliderWidth;
				filledPath.visible = true;
				
				pointer.x = filledPath.width;
			}

			
		}
		
		
		
		
		
		/**
		 * Validate whether current value is correct or not.
		 * @return
		 */
		private function validate():Boolean
		{
			if (_value >= _minValue && _value <= _maxValue) return true;
			
			if (_value < _minValue) Value = _minValue;
			else Value = _maxValue;
			return false;
		}
		
		
		
		
		
		
		/**
		 * Instantiate a slider.
		 * @param	backgroundPath
		 * @param	pointerSprite
		 * @param	backgrounfPathFilledSprite
		 */
		public function Slider(slideWidth:Number=300,backgroundPath:DisplayObject=null,pointerDisplayObject:DisplayObject=null,backgrounfPathFilledDisplayObject:DisplayObject=null) 
		{
			sliderWidth = slideWidth;
			if (backgroundPath != null)
			{
				path = backgroundPath;
			}
			
			if (pointerDisplayObject != null)
			{
				_pointerDisplayObject = pointerDisplayObject;
			}
			
			if (backgrounfPathFilledDisplayObject != null)
			{
				filledPath = backgrounfPathFilledDisplayObject;
			}
			
			init();
		}
		
		
		
		
		
		
		/**
		 * init vars and ui
		 */
		private function init()
		{
			if (path == null)
			{
				var shape:Shape = new Shape();
				shape.graphics.beginFill(0xCCBBCC, 1); 
				shape.graphics.drawRect(0, 0, sliderWidth, sliderHeight);
				shape.graphics.endFill();
				
				path = shape;
			}
			pathOriginalWidth = path.width;
			pathWidthRatio = sliderWidth / pathOriginalWidth;
			
			path.width = sliderWidth;
			pathSprite.addChild(path);
			addChild(pathSprite);
			
			
			if (filledPath == null)
			{
				var shape2:Shape = new Shape();
				shape2.graphics.beginFill(0x334455, 1); 
				shape2.graphics.drawRect(0, 0, sliderWidth, sliderHeight);
				shape2.graphics.endFill();
				
				filledPath = shape2;
			}
			filledPath.width = sliderWidth;
			var filledPathSprite:Sprite = new Sprite();
			filledPathSprite.addChild(filledPath);
			filledPathSprite.mouseEnabled = false;
			filledPathSprite.mouseChildren = false;
			addChild(filledPathSprite);
			
			
			if (_pointerDisplayObject == null)
			{
				var triangleHeight:uint = 30;
				var triangleFloor:uint = 30;
				var triangleShape:Shape = new Shape();
				triangleShape.graphics.beginFill(0x2147AB);
				triangleShape.graphics.lineTo(triangleFloor/2, triangleHeight);
				triangleShape.graphics.lineTo(-triangleFloor/2, triangleHeight);
				triangleShape.graphics.lineTo(0, 0);
				_pointerDisplayObject = triangleShape;
			}
			pointer.addChild(_pointerDisplayObject);
			addChild(pointer);
			
			var rect:Rectangle = path.getRect(this);
			rect.width = sliderWidth;
			rect.height = .01;
			pointer.startDrag(false, rect);
			pointer.stopDrag();
			
			pointer.x = 0;
			
			Value = 0;
			
			
			// Adding required handlers
			pathSprite.addEventListener(MouseEvent.CLICK, On_Path_Clicked);
			timer.addEventListener(TimerEvent.TIMER, On_TimerEvent);
			pointer.addEventListener(MouseEvent.MOUSE_DOWN, onPointer_MouseDown);
			pointer.addEventListener(MouseEvent.MOUSE_UP, onPointer_MouseUp);
			pointer.addEventListener(MouseEvent.MOUSE_OUT, onPointer_MouseUp);
		}
		
		
		
		
		
		/**
		 * Resetting event generation for performance.
		 * @param	type
		 */
		private function resetEventGeneration(type:String)
		{
			switch(type)
			{
				case SliderEvent.MOUSE_ON_VALUE:
					if (this.hasEventListener(SliderEvent.MOUSE_ON_VALUE))
					{
						if(!pathSprite.hasEventListener(MouseEvent.MOUSE_MOVE)) pathSprite.addEventListener(MouseEvent.MOUSE_MOVE, On_Path_MouseMove);
					}
					else if (pathSprite.hasEventListener(MouseEvent.MOUSE_MOVE)) pathSprite.removeEventListener(MouseEvent.MOUSE_MOVE,On_Path_MouseMove);
					break;
				
				
				case SliderEvent.VALUE_CHANGED:
					_hasValueChangeHandler = this.hasEventListener(SliderEvent.VALUE_CHANGED);
					break;
			}
		}
		
		
		
		
		
		
		private function On_Path_Clicked(e:MouseEvent)
		{
			pointer.x = e.localX*pathWidthRatio;
			Value = _minValue + e.localX * pathWidthRatio / sliderWidth * _range;
			dispatchEvent(new SliderEvent(SliderEvent.VALUE_CHANGED, this, _value, _value));
		}
		
		
		
		
		
		
		
		private function On_Path_MouseMove(e:MouseEvent)
		{
			dispatchEvent(new SliderEvent(SliderEvent.MOUSE_ON_VALUE, this, _value, _minValue + e.localX * pathWidthRatio / sliderWidth * _range));
		}
		
		
		
		
		
		
		
		
		private function onPointer_MouseDown(e:*)
		{
			if (dragging == false)
			{
				var rect:Rectangle = path.getRect(this);
				rect.width = sliderWidth;
				rect.height = .01;
			
				dragging = true;
				
				
				pointer.startDrag(false, rect);
				timer.start();
			}
		}
		
		
		
		
		
		
		
		private function onPointer_MouseUp(e:*)
		{
			if (dragging)
			{
				dragging = false;
				
				pointer.stopDrag();
				timer.stop();
				On_TimerEvent(null);
			}
		}
		
		
		
		
		
		
		private function On_TimerEvent(e:*)
		{
			Value = _minValue + pointer.x / sliderWidth * _range;
			if(_hasValueChangeHandler) dispatchEvent(new SliderEvent(SliderEvent.VALUE_CHANGED, this, _value, _value));
		}
	}

}